package site.tiangao.async;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SpringBootApplication
@RestController
public class NormalServer {

    @Value("${test.url}")
    String url;

    ExecutorService executor = Executors.newFixedThreadPool(200);

    RestTemplate restTemplate = new RestTemplate();

    public static void main(String[] args) {
        SpringApplication.run(NormalServer.class);
    }

    @GetMapping("/dal")
    public String dal() throws InterruptedException {
        Thread.sleep(5);
        System.out.println(Thread.currentThread().getName() + " ---- dal ");
        return "dal ok";
    }

    @GetMapping("/redis")
    public String redis() throws InterruptedException {
        Thread.sleep(2);
        System.out.println(Thread.currentThread().getName() + " -- redis ");
        return "dal ok";
    }

    @GetMapping("/image")
    public String image() throws InterruptedException {
        Thread.sleep(15);
        System.out.println(Thread.currentThread().getName() + " ------ image ");
        return "dal ok";
    }


    @GetMapping("/sss")
    public String sss() throws InterruptedException {
        Thread.sleep(25);
        System.out.println(Thread.currentThread().getName() + " --------- sss ");
        return "dal ok";
    }

    @GetMapping("/hello")
    public String hello() throws InterruptedException {
        Thread.sleep(100);
        return "hello world";
    }

    @GetMapping("/mid")
    public String set() throws ExecutionException, InterruptedException {
        CompletableFuture<String> dal = CompletableFuture.supplyAsync(() -> restTemplate.getForObject(url + "/dal", String.class), executor);
        CompletableFuture<String> redis = CompletableFuture.supplyAsync(() -> restTemplate.getForObject(url + "/redis", String.class), executor);
        CompletableFuture<String> image = CompletableFuture.supplyAsync(() -> restTemplate.getForObject(url + "/image", String.class), executor);
        CompletableFuture<String> sss = CompletableFuture.supplyAsync(() -> restTemplate.getForObject(url + "/sss", String.class), executor);

        return String.format("%s %s %s %s", dal.get(), redis.get(), image.get(), sss.get());
    }

}
